import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_vehicle.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/encrypt_mixin.dart';
import 'package:inmotion_pro/pages/mixin/http_request_mixin.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/pages/models/user_model.dart';
import 'package:inmotion_pro/pages/models/vehicle_model.dart';
import 'package:inmotion_pro/pages/others/common_enum/vehicle_owner_type.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'state.dart';

// 车辆授权用户列表控制器
class VehicleAuthUserListController extends GetxController
    with
        EncryptionMixin,
        CacheMixin,
        HttpRequestMixin,
        BluetoothMixin,
        RealtimeInfoMixin {
  // 状态
  final VehicleAuthUserListState state = VehicleAuthUserListState();

  // 车辆模型
  VehicleModel get vehicleModel =>
      Get.arguments != null ? Get.arguments as VehicleModel : VehicleModel();

  // 我的授权用户模型
  UserModel myAuthorizedUserModel = UserModel.fromMap({});

  @override
  void onInit() {
    super.onInit();
    // 刷新数据
    refreshData();
  }

  // 刷新数据
  refreshData() {
    httpRequestMixinRequestAuthorizedUserList(
      vehicleModel.sn,
      (p0) {
        if (p0.$1.isNotEmpty) {
          // 根据车主类型排序，主车主在前面，副车主在后面
          p0.$1.sort((a, b) => a.ownerType.val - b.ownerType.val);
          state.authUserList.value = p0.$1;
          // 获取我的授权用户模型
          for (var userModel in p0.$1) {
            if (userModel.uid == GlobalService.to.cacheUserInfo.value.uid) {
              myAuthorizedUserModel = userModel;
              break;
            }
          }
        } else {
          state.authUserList.value = [];
        }
      },
      showLoading: false,
      onError: (err) {
        state.authUserList.value = [];
      },
    );
  }

  // 解绑主车主
  disbandOwnerOnTap() {
    LxAlert.show(
        title: local.prompt_title,
        local.unbind_owner_desc,
        cancelTitle: local.cancel,
        confirmTitle: local.confirm,
        contentTextAlign: TextAlign.center, confirmCallback: (e) {
      Loading.showLoading(null);
      ApiHelper().cancelCertificationOwner(vehicleModel.sn).then((success) {
        if (success) {
          _deleteVehicleCacheAfterDisbandOwner();
        } else {
          Loading.showError(local.unbind_failed);
        }
      }).catchErrorHandler();
    });
  }

  // 解绑副车主
  disbandSecondOwnerOnTap(UserModel userModel) {
    LxAlert.show(
        title: local.prompt_title,
        local.unbind_secondary_owner_desc,
        cancelTitle: local.cancel,
        confirmTitle: local.confirm, confirmCallback: (e) {
      Loading.showLoading(null);
      ApiHelper()
          .cancelCertificationSecondaryOwner(vehicleModel.sn,
              userId: userModel.ownerType == VehicleOwnerType.owner
                  ? userModel.uid
                  : null) // 主车主解绑副车主时，需要传userId，副车主解绑自己时不需要
          .then((success) {
        if (success) {
          _deleteVehicleCacheAfterDisbandOwner();
        } else {
          Loading.showError(local.unbind_failed);
        }
      }).catchErrorHandler();
    });
  }

  // 主车主/副车主解绑后，需要删除本地缓存的该车辆
  Future<void> _deleteVehicleCacheAfterDisbandOwner() async {
    // 停止轮询获取车辆实时数据
    return realtimeInfoMixinStopLoopToGetVehicleRealTimeData()
        .then(
            (value) => cacheMixinDeleteCacheVehicle(vehicleModel.bleName))
        .then((success) async {
      if (success) {
        VechileConnectionService.to.bluetoothConnectHelper!.disconnect().then((_) {
          Loading.showSuccess(local.unbind_success);
          Get.until((route) => route.settings.name == AppRoutes.ROOT);
        });
      } else {
        Loading.showError(local.logout_failed);
      }
    });
  }
}
